package fw_db_self

import (
	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"sync"
	"time"
	"transport/framework/fw_config"
	"transport/framework/fw_db/fw_db_self/db_sqlite_plugin"
	"transport/framework/fw_log"
)

var (
	db     *gorm.DB
	dbLock *sync.RWMutex
	once   sync.Once
)

func DbInit() {
	once.Do(func() {
		var err error
		dbLock = new(sync.RWMutex)
		db, err = gorm.Open(sqlite.Open(fw_config.GetConfigHandler().GetString("db.sqlite.path")), &gorm.Config{
			NamingStrategy: schema.NamingStrategy{SingularTable: true},
			Logger:         logger.Default.LogMode(logger.Info),
			//SkipDefaultTransaction: true,
		})
		if err == nil {
			fw_log.Slogger.Info("数据库打开成功")
		} else {
			fw_log.Slogger.Info("数据库打开失败")
			return
		}
		sqlDB, err := db.DB()
		if err != nil {
			fw_log.Slogger.Info("通用数据库对象获取失败")
			return
		}
		if err != nil {
			sqlDB.Close()
			fw_log.Slogger.Info("数据库同步失败")
			return
		}
		sqlDB.SetMaxOpenConns(fw_config.GetConfigHandler().GetInt("db.sqlite.maxOpenConns"))
		sqlDB.SetMaxIdleConns(fw_config.GetConfigHandler().GetInt("db.sqlite.maxIdleConns"))
		sqlDB.SetConnMaxIdleTime(time.Hour)
		db.Use(&db_sqlite_plugin.QueryBeforePlugin{})
		db.Use(&db_sqlite_plugin.CreateBeforePlugin{})
		db.Use(&db_sqlite_plugin.UpdateBeforePlugin{})
		//err = db.AutoMigrate(&web_model.LsDrug{})
		//if err != nil {
		//	fw_log.Slogger.Info("err----->", err.Error())
		//}
	})
}
func GetSqliteDB() *gorm.DB {
	return db
}
func GetSqliteLock() *sync.RWMutex {
	return dbLock
}
